<?php
require_once(LIB_PATH.'PHPMailer-5.2.6/class.phpmailer.php');


class JapwordMail extends JapwordView {
	
	public $to;
	public $from;
	public $fromName;
	public $title;
	
	private $body;
	
	public function __construct() {
		parent::__construct();
		
		$this->from = MAIL_FROM;
		$this->fromName = MAIL_FROM_NAME;
		
		$this->logmail_path = RACINE_PATH.'temp/log_mails/';
	}
	
	public function send($tpl) {

		$mail = new PHPMailer();
		$mail->From = $this->from;
		$mail->FromName = $this->fromName;
		$mail->AddAddress($this->to);
		$mail->AddReplyTo($this->replyto);
		$mail->IsHTML(true);
		$mail->CharSet = 'UTF-8';
		
		$mail->Subject = "Japword - $this->title";
		$mail->Body    = $this->display($tpl, array('output' => false));
		$result = $mail->Send();

		if (defined('JAPWORD_MAIL_LOG') && JAPWORD_MAIL_LOG) {
			$this->writeMailToLogFile();
			
		}
		if (!$result) {
			error_log("[JapwordMail] Impossible d'envoyer le mail. Erreur: ".$mail->ErrorInfo);
		}
		
		if (defined('JAPWORD_MAIL_MODE_DEV') && JAPWORD_MAIL_MODE_DEV) {
			$result = true;
		}
		
		return $result;
	}
	
	public function writeMailToLogFile() {
		$filename = date('Ymd_His').'.'.time().'.'.$this->from.' - '.$this->to.'.html';
		$contents = "<!-- Sujet: $this->title -->\n";
		$contents .= $this->body;
		
		$path = $this->logmail_path.$filename;
		if (file_exists($path)) {
			unlink($path);
		}
		file_put_contents($this->logmail_path.$filename, $contents);
	}
}